import { Marked } from 'marked'
import { markedHighlight } from "marked-highlight";
import hljs from 'highlight.js'
import { DomUtils } from 'htmlparser2'
import { dom } from '../util'

// const {markedHighlight} = globalThis.markedHighlight;
const marked = new Marked(
    markedHighlight({
        highlight(code: string, lang: string, _info) {
            return hljs.highlightAuto(code, [lang]).value
        }
    })
);

const renderer = new marked.Renderer()

// 标签上添加class=`md-tag`
function tagAddClassName(source: string) {
    let element = dom.make(source)
    let elems = DomUtils.getElementsByTagName(() => true, element, true)
    elems.forEach((elem: any) => {
        elem.attribs = elem.attribs || {}
        elem.attribs.class = [elem.attribs.class || '', `md-${elem.name}`].filter(name => !!name).join(' ')
    })
    return DomUtils.getOuterHTML(element)
}

// table
renderer.table = (header: string, body: string): string => {
    return `<table class="md-table">
    ${tagAddClassName(header)}
    ${tagAddClassName(body)}
  </table>`
}

// h1 - h6
renderer.heading = (text: string, level: number, raw: string): string => {
    return `<h${level} class="md-h${level}">${text}</h${level}>`
}

// code
renderer.code = (code: string, language: string, isEscaped: boolean): string => {
    code = hljs.highlightAuto(code).value
    return `<code class="lang-${language} md-code">${code}</code>`
}

// init
marked.setOptions({
    renderer
})

// MD 转 HTML
function md2html(source: string, isFormat: boolean) {
    source = md.marked.parse(source) as string

    // 格式化：换行、缩进
    if (isFormat) {
        source = source.replace(/\n/g, '<br/>')
        source = source.replace(/[ ]{2}/g, '<span class="md--tab"></span>')
    }
    return source
}

export const md = {
    marked,
    md2html
}